<template>
  <div class="baseDialog">
    <div>
      <el-drawer ref="drawer" :visible.sync="drawer" direction="rtl" size="90%" :destroy-on-close="true"
                 :before-close="handleClose">
        <template v-slot:title>
          <div>
            {{title}} <el-switch v-model="crossFlag" active-value="1" inactive-value="0" @change="handleSwitch"></el-switch>&nbsp;{{ $i18n.t('mesTechnology.crossShop') }}
          </div>
        </template>
        <div style="display: flex; width: 100%; height: calc(100% - 50px); overflow:hidden;" v-loading="isLoading">
          <!-- 三列：左侧车间列表 -->
          <div class="drawer-left">
            <el-checkbox v-model="isSelectedAll" @change="handleSelectedAll">{{ $i18n.t('mesTechnology.allWorkshop') }}</el-checkbox>
            <el-scrollbar style="width: 100%; height: 100%; padding-bottom: 30px;">
              <el-checkbox-group v-model="selectedWorkshopList" @change="handleWorkshopChange" class="workshop-list">
                <el-checkbox v-for="(item, index) in workshopList" :label="item.modelingName" :key="index"></el-checkbox>
              </el-checkbox-group>
            </el-scrollbar>
          </div>
          <!-- 三列：中间工序列表 -->
          <div class="drawer-middle">
            <div class="search-form">
              <ele-form-search
                :formConfig="searchConfig"
                ref="eleFormSearch"
                @handleSearch="handleSearch"
                @handleReset="handleReset"
              ></ele-form-search>
            </div>
            <lb-table
              style="flex-grow: 1"
              v-table-max-height
              height="99%"
              ref="processList"
              :column="column"
              :pagination="false"
              :data="processList"
              border
              @selection-change="handleSelectionChange"
            >
            </lb-table>
          </div>
          <!-- 三列：右侧已选工序列表 -->
          <div class="drawer-right">
            <lb-table ref="selectedProcess" :column="selectedProcessColumn" :data="selectedProcessList" border :pagination="false">
            </lb-table>
          </div>
        </div>
        <div style="height: 50px; display: flex; align-items: center;">
          <el-button type="primary" @click="handleSubmit" :disabled="isLoading">{{ $i18n.t('common.submit') }}</el-button>
          <el-button @click="drawer = false" :disabled="isLoading">{{ $i18n.t('common.cancel') }}</el-button>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { getProcessList, getProcessTypeIdList, getConfigurationItem, getWorkshopList } from '@/api/process/mesTechnologyOperate';
import LbTable from '@/components/lb-table/lb-table';
import eleFormSearch from "@/components/ele-form-search/index";
import { uniqueKey } from '@/utils/judge'

export default {
  name: 'WorkingDialog',
  components: {
    LbTable, eleFormSearch
  },
  props: {
    title: {
      type: String,
      default: $i18n.t('mesTechnology.selectProcess')
    },
    // 选中的工序列表
    selectedProcess: {
      type: Array,
      default: () => []
    },
    // 是否可以跨车间
    crossShopFlag: {
      type: String,
      default: '0'
    }
  },
  data() {
    return {
      drawer: false,
      isLoading: false,
      loading: false,
      selfHeight: 0,
      searchConfig: {
        inline: true,
        formDesc: {
          processTypeId: {
            layout: 12,
            type: 'select',
            label: $i18n.t('mesTechnology.processTypeId'),
            prop: {
              value: 'id',
              text: 'processTypeName'
            },
            options: async (data) => {
              const list = await getProcessTypeIdList()
              return list.data.result
            }
          },
          processCode: {
            layout: 12,
            type: 'input',
            label: $i18n.t('mesTechnology.processCode')
          },
          processName: {
            layout: 12,
            type: 'input',
            label: $i18n.t('mesTechnology.processName')
          }
        }
      },
      // 列表页字段的绑定配置
      column: [
        {
          type: 'selection'
        },
        {
          prop: 'processCode',
          label: $i18n.t('mesTechnology.processCode'),
          minWidth: 120,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'processName',
          label: $i18n.t('mesTechnology.processName'),
          minWidth: 120,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'processTypeId',
          label: $i18n.t('mesTechnology.processTypeId'),
          showOverflowTooltip: true,
          minWidth: 140,
          align: 'center',
          optionProp: {
            value: 'id',
            label: 'processTypeName'
          },
          option: async (data) => {
            const list = await getProcessTypeIdList()
            return list.data.result
          }
        },
        {
          prop: 'workshopCode',
          label: $i18n.t('mesTechnology.workshopCode'),
          minWidth: 120,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'workshopName',
          label: $i18n.t('mesTechnology.workshopName'),
          minWidth: 140,
          align: 'center',
          showOverflowTooltip: true
        }
      ],
      params: {},
      crossFlag: '0',  // 是否可以跨车间
      workshopList: [],  // 车间列表
      selectedWorkshopList: [],  // 已选择车间列表
      isSelectedAll: false,  // 是否选择全部车间
      processList: [],  // 工序列表
      selectedProcessList: [],  // 选中的工序列表
      processOperateList: [  // 选中工序列表的操作按钮
        {
          label: $i18n.t('common.delete'),
          handleName: 'delete',
          icon: 'el-icon-delete',
          type: 'danger'
        }
      ],
      selectedProcessColumn: [  // 选中工序表格Column
        {
          type: 'index',
          label: $i18n.t('common.order'),
          align: 'center',
          width: 60
        },
        {
          prop: 'processCode',
          label: $i18n.t('mesTechnology.processCode'),
          minWidth: 120,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'processName',
          label: $i18n.t('mesTechnology.processName'),
          minWidth: 140,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'workshopName',
          label: $i18n.t('mesTechnology.workshopName'),
          minWidth: 120,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'operate',
          label: $i18n.t('common.operation'),
          align: 'center',
          width: 80,
          render: (h, scope) => {
            return <ele-row-operation scope={scope} rowConfig={this.rowConfig} onRowOperate={this.rowOperate} />
          }
        }
      ],
      rowConfig: [
        {
          name: $i18n.t('common.delete'),
          type: 'danger',
          class: 'row-btn-primary',
          handleName: 'delete' //点击时返回的标识
        },
      ],
      isTransfer: true,  // 是否转移到选中工序列表
    }
  },
  created() {},
  computed: {},
  methods: {
    init(params) {
      this.params = params;
      let selectedProcessList = [];
      this.selectedProcess.forEach(item => {
        this.selectedWorkshopList.push(item['baseInfo'].workshopName);
        selectedProcessList.push({
          id: item['baseInfo'].id,
          processCode: item['baseInfo'].processCode,
          processName: item['baseInfo'].processName,
          workshopName: item['baseInfo'].workshopName,
        })
      })
      this.selectedProcessList = selectedProcessList;
      this.getProcessList();
      this.getWorkshopList();
      this.drawer = true;
    },
    // 获取工序列表
    getProcessList() {
      getProcessList(this.params).then(res => {
        const currentSelectedProcess = res.data.result.filter(item => this.selectedProcessList.find(process => process.id === item.id));
        this.processList = [ ...currentSelectedProcess, ...res.data.result] || [];
        this.processList = uniqueKey([...this.processList], 'id');
        this.$nextTick(() => {
          this.isTransfer = true;
          this.updateProcessCheckStatus(this.selectedProcessList);
        })
      }).finally(() => this.isLoading = false )
    },
    // 获取车间列表
    getWorkshopList() {
      const params = {
        modelingCode: this.$store.getters.factoryCode || '',
        level: '4',
        modelingType: '0'
      }
      getWorkshopList(params).then(res => {
        this.workshopList = res.data.result || [];
      })
    },
    handleClose(done) {
      done()
    },
    // 所有车间选择
    handleSelectedAll(val) {
      this.selectedWorkshopList = val ? [...this.workshopList.map(item => item.modelingName)] : [];
      this.handleSearch();
    },
    // 车间选择
    handleWorkshopChange() {
      this.isSelectedAll = this.selectedWorkshopList.length === this.workshopList.length;
    },
    // 表格行操作事件
    rowOperate({ handleName, name, row }) {
      const fnc = {
        delete: () => {
          this.$confirm($i18n.t('common.deleteSingle',{name:$i18n.t('mesTechnology.process')}), $i18n.t('common.tip'), {
            confirmButtonText: $i18n.t('common.ok'),
            cancelButtonText: $i18n.t('common.cancel'),
            type: 'warning'
          }).then(() => {
            this.selectedProcessList = this.selectedProcessList.filter(item => item.id !== row.id);
            this.$nextTick(() =>{
              this.updateProcessCheckStatus(this.selectedProcessList);
            })
          })
        }
      }
      fnc[handleName]()
    },
    // 更新工序列表checkbox选中状态
    updateProcessCheckStatus(data) {
      if (data.length > 0) {
        this.$refs['processList'].clearSelection();
        data.forEach(row => {
          const res = this.processList.find(item => item.id === row.id);
          if (res) {
            this.$refs['processList'].toggleRowSelection(res, true);
          }
        })
      } else {
        this.$refs['processList'].clearSelection();
      }
    },
    // 选中工序执行
    handleSelectionChange(data) {
      if (this.crossFlag !== '1' && data.length > 0 && this.selectedProcessList.length > 0) {
        const selectedWorkshop = this.selectedProcessList[0].workshopCode;
        if (selectedWorkshop && !data.every(item => item['workshopCode'] === selectedWorkshop)) {
          this.$message.error($i18n.t('mesTechnology.processDifferent'));
          this.$nextTick(() =>{
            this.updateProcessCheckStatus(this.selectedProcessList);
          })
          return;
        }
      }
      if (this.isTransfer) {
        // 删除不在data中的工序，保留在data中的工序，和其他车间的工序
        this.processList.forEach(item => {
          this.selectedProcessList = this.selectedProcessList.filter(process => process.id !== item.id);
        })
        this.selectedProcessList = [...this.selectedProcessList, ...data];
        this.selectedProcessList = JSON.parse(JSON.stringify(this.selectedProcessList));
        this.selectedProcessList = uniqueKey([...this.selectedProcessList], 'id');
      }
    },
    // 表单搜索
    handleSearch() {
      // this.saveSelectedProcessList();
      this.isLoading = true;
      this.isTransfer = false;
      this.params = { ...this.params, ...this.$refs.eleFormSearch.formData }
      this.getProcessList();
    },
    // 表单重置
    handleReset() {
      this.isLoading = true;
      this.isTransfer = false;
      this.params = { ...this.$refs.eleFormSearch.formData }
      this.getProcessList();
    },
    // 将选中的工序列表保存一个副本，便于还原选中状态
    saveSelectedProcessList() {
      if (this.selectedProcessList.length > 0) {
        // this.selectedProcessListCopy = JSON.parse(JSON.stringify(this.selectedProcessList));
      }
    },
    // 提交表单
    handleSubmit() {
      this.$emit('selectedProcessList', { list: this.selectedProcessList, crossShopFlag: this.crossFlag });
      this.drawer = false;
    },
    handleSwitch(data) {
      if (data === '0') {
        if (this.selectedProcessList.length > 0) {
          const selectedWorkshop = this.selectedProcessList[0].workshopCode
          if (!this.selectedProcessList.every(item => item['workshopCode'] === selectedWorkshop)) {
            this.$message.error($i18n.t('mesTechnology.errorHint3'));
            this.crossFlag = '1';
          }
        }
      }
    }
  },
  watch: {
    crossShopFlag: {
      handler(val) {
        this.crossFlag = val;
      },
      immediate: true,
    },
    selectedWorkshopList: {
      handler: _.debounce(function (data) {
        this.isLoading = true;
        const workshopList = data.map(item => this.workshopList.find(workshop => workshop.modelingName === item)?.modelingCode);
        if (workshopList.length > 0) {
          this.params = { ...this.params, workshopCodes: workshopList.join(',') }
        } else {
          this.params = { ...this.params, workshopCodes: '-1' }
        }
        this.handleSearch()
      }, 1000)
    }
  }
}
</script>
<style lang="scss" scoped>
.baseDialog {
  /deep/ .el-drawer__body {
    padding: 0 10px;
  }

  /deep/ .ele-form-search {
    height: auto !important;
  }

  .workshop-list {
    /deep/ .el-checkbox {
      display: block;
      margin-top: 10px;
    }
  }
  .drawer-left {
    flex: 0 0 200px;
    padding-right: 10px;
    overflow: hidden;
  }

  .drawer-middle {
    flex: 1 1;
    width: 400px;
    display: flex;
    flex-direction: column;
  }

  .drawer-right {
    flex: 0 0 400px;
    padding-left: 10px;
  }
  /deep/ .el-loading-spinner {
    left: 50%;
  }
}
</style>
